package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * 处理社交登录请求
 *
 * @author ly
 */
@Slf4j
@Controller
@AllArgsConstructor(onConstructor_ = @Autowired)
public class OAuth2Controller {

    private final MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        log.info("获得的code为：" + code);
        Map<String, String> map = new HashMap<>(5);
        map.put("client_id", "978472938");
        map.put("client_secret", "636ec3a8d4ce811b08c6fbafbbec7b8c");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        //1、根据获得的code向微博发送请求获得accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), null, map);
        //2、根据返回结果进行处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //成功获取到了accessToken
            //拿到响应头内容
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //1)、将社交用户信息与会员数据库信息进行绑定（自动注册）
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            //如果调用远程服务登录成功
            if (oauthLogin.getCode() == 0) {
                //拿到返回的数据
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息：" + data.toString());
                //1、第一次使用session：
                //TODO 1、默认发的令牌。session=dsajhdjl。作用域。当前域;（解决子域session共享间题)

                //TODO 2、使用JSON的序列化方式来序列化对象数据到redis中

                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                //登录成功跳转回首页
                return "redirect:http://gulimall.com";
            } else {
                //登录失败重新登录
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
